<template>
  <div>
    <el-card style="height: 80px;">
      <el-form :inline="true" class="search_form">
        <el-form-item label="用户名:">
          <el-input v-model="keyword" placeholder="请输入搜索用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="keyword ? false : true" @click="serach">搜索</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0px; ">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button type="danger" :disabled="selectIdArr.length > 0 ? false : true"
        @click="deleteSelectUser">批量删除</el-button>
      <!-- table展示用户信息 -->
      <el-table @selection-change="selectChange" style="margin: 10px 0px;" border :data="userArr">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column label="#" type="index" align="center"></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column label="用户名字" align="center" prop="username"></el-table-column>
        <el-table-column label="用户名称" align="center" prop="name"></el-table-column>
        <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="280px" align="center">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
            <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
            <el-popconfirm :title="`你确定要删除${row.username}`" width="260px" @confirm="deleteUser(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 7, 9, 11]"
        layout=" prev, pager, next, jumper,->,sizes,total" :total="total" :background="true"
        @current-change="getHasUser" @size-change="handler" />
    </el-card>
    <!-- 抽屉结构添加|更新用户 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form label-width="100px" :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input v-model="userParams.username" placeholder="请你输入用户姓名"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input v-model="userParams.name" placeholder="请你输入用户昵"></el-input>
          </el-form-item>
          <el-form-item v-if="userParams.id ? false : true" label="用户密码" prop="password">
            <el-input v-model="userParams.password" placeholder="请你输入用户密码"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto;">
          <el-button type="default" @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确认</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 抽屉结构(已有角色进行分配) -->
    <el-drawer v-model="drawer1">
      <template #header>
        <h4>分配用户角色</h4>
      </template>
      <template #default>
        <el-form label-width="100px">
          <el-form-item label="用户姓名">
            <el-input :disabled="true" v-model="userParams.username"></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
              全选
            </el-checkbox>
            <el-checkbox-group @change="handleCheckedCitiesChange" v-model="userRole">
              <el-checkbox v-for="(role, index) in allRole" :key="index" :label="index" :value="role">
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto;">
          <el-button type="default" @click="drawer1 = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup lang='ts' name='user'>
import useLayOutSettingStore from '@/store/modules/setting';
import { nextTick, onMounted, reactive, ref } from 'vue';
import { reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole, reqRemoveUser, reqSelectUser } from '@/api/acl/user';
import type { Records, User, UserResponseData, AllRoleResponseDate, AllRole, SetRoleData } from '@/api/acl/user/type';
import { ElMessage } from 'element-plus';
let pageNo = ref<number>(1)
let pageSize = ref<number>(5)
//用户总个数
let total = ref<number>(0)
//全部用户账号信息
let userArr = ref<Records>([])
//收集用户信息
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
let drawer1 = ref<boolean>(false)
//获取form表单实例
let formRef = ref<any>()
//是否全选样式boolean
let checkAll = ref<boolean>(false)
//是否不稳定样式boolean
let isIndeterminate = ref(true)
//全部职位
let allRole = ref<AllRole>([])
//选中职位
let userRole = ref<AllRole>([])
//准备一个数组存储批量删除的用户ID
let selectIdArr = ref<User[]>([])
//收集搜索框数据
let keyword = ref<string>('')
//拿取仓库对象
let settingStore = useLayOutSettingStore()
onMounted(() => {
  getHasUser()
})
//获取全部已有的用户信息
const getHasUser = async (pager = 1) => {
  pageNo.value = pager
  let result: UserResponseData = await reqUserInfo(pageNo.value, pageSize.value,keyword.value)
  if (result.code == 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}
//下拉菜单变化回调
const handler = () => {
  getHasUser()
}
//添加用户按钮回调
const addUser = () => {

  drawer.value = true
  //每次添加时清空input表单原有输入
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  //清除上一次错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
//用户编辑按钮回调
//row为已有用户信息
const updateUser = (row: User) => {
  //清除上一次错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
  drawer.value = true
  Object.assign(userParams, row)
}
//保存按钮回调（更新或添加）
const save = async () => {
  console.log(123456)
  //点击保存按钮时，务必保证表单符合条件
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({ type: 'success', message: userParams.id ? '更新成功' : "添加成功" })
    //刷新会自动回到第一页所有getHasUser无用了
    // getHasUser(userParams.id ? pageNo.value : 1)
    //浏览器自动刷新一次  (permission.ts写了路由跳转会检验账号是否存在)
    window.location.reload()

  } else {
    drawer.value = false
    ElMessage({ type: 'error', message: userParams.id ? '更新失败' : "添加失败" })
  }
}
//取消按钮回调
const cancel = () => {
  drawer.value = false
}
//校验名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
//校验昵称回调函数
const validatorname = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('昵称名字至少五位'))
  }
}
//校验密码回调函数
const validatorpassword = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('密码至少六位'))
  }
}
//表单校验规则对象
const rules = {
  username: [{ requried: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ requried: true, trigger: 'blur', validator: validatorname }],
  password: [{ requried: true, trigger: 'blur', validator: validatorpassword }],
}
//分配角色按钮回调
const setRole = async (row: User) => {
  Object.assign(userParams, row)
  //获取全部职位数据与当前用户已有职位数据
  let result: AllRoleResponseDate = await reqAllRole((userParams.id as number))
  if (result.code == 200) {
    //获取所有职位和当前职位
    allRole.value = result.data.allRolesList
    userRole.value = result.data.assignRoles
    // 获取成功抽屉显现
    drawer1.value = true
  }
}
//全选框改变回调
const handleCheckAllChange = (val: boolean) => {
  //val: true:全选   false:未全选
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
// 角色框选中回调
const handleCheckedCitiesChange = (value: string[]) => {
  //value是userRole数组
  const checkedCount = value.length
  //长度和全部的一样 则是全选
  checkAll.value = checkedCount === allRole.value.length
  //长度>0 但 小于全部长度  不稳定状态为true
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}
//分配角色确认按钮
const confirmClick = async () => {
  let data: SetRoleData = {
    userId: (userParams.id as number),
    roleIdList: userRole.value.map(item => {
      return (item.id as number)
    })
  }
  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '分配成功' })
    drawer1.value = false
    getHasUser(pageNo.value)
  } else {
    ElMessage({ type: 'error', message: '分配失败' })
    drawer1.value = false
  }


}
// 单个删除
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({ type: 'error', message: '删除失败' })
  }
}
//批量删除
//勾选中时获取数据
const selectChange = (value: any) => {
  //value带的是选中的每一行的数据所组成的输出
  selectIdArr.value = value
}

const deleteSelectUser = async () => {
  //整理批量删除参数
  let idsList: any = selectIdArr.value.map(item => {
    return item.id
  })
  console.log('idlist', idsList)
  let result: any = await reqSelectUser(idsList)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({ type: 'error', message: '删除失败' })
  }
}
//搜索按钮回调
const serach = () => {
  //搜索与获取一样
  getHasUser()
  keyword.value = ''
}
//重置按钮
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
</script>



<style scoped>
.search_form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>